import { Button, Modal, Space, Row, Col, Image, message, Tag, Badge } from 'antd';
import { CopyOutlined, createFromIconfontCN, EditOutlined } from '@ant-design/icons';
import React, { useState, useRef, useEffect } from 'react';
import { history, getDvaApp } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import moment from 'moment';
import $utils from '@/utils/utils';
import { billStatusTypes, deliveryWayData, statusData } from '@/utils/common';
// 订单接口导入
import {
  changePhone,
  billReturn,
  deliveryCheckout,
  getDeliveryLog,
  historyOrderList,
} from '@/services/delivery';
// 驿站接口导入
import { getStationName } from '@/services/postHouse';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_3354826_k42a89lunf.js',
});

// 退回原因
const reasonList = [
  { label: '无人接听', value: 1 },
  { label: '拒收件', value: 2 },
  { label: '错分件', value: 3 },
  { label: '改地址', value: 4 },
  { label: '逾期件', value: 5 },
  { label: '遗失件', value: 6 },
  { label: '破损件', value: 7 },
  { label: '非手机号', value: 8 },
  { label: '快递公司追回', value: 9 },
  { label: '停机关机', value: 10 },
  { label: '家属区', value: 11 },
  { label: '自取', value: 12 },
  { label: '转寄', value: 13 },
  { label: '其它', value: 14 },
];

const storageTypes = [
  { label: '货架', value: 1 },
  { label: '柜体', value: 3 },
  { label: '暂存区', value: 4 },
];

const DeliveryList: React.FC = () => {
  // 解决无法调用dispatch
  const dispatch = getDvaApp()._store.dispatch;

  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const [initParams, setParams] = useState<any>();
  const [rotation, handleUpdRotation] = useState<number>(0);
  const [img_zoom] = useState<number>(100);
  const [dataSource, setDataSource] = useState<any[]>([]);

  const [collapsed, setCollapsed] = useState<boolean>(false);
  // table列表内容滚动区域的高度
  const [scrollY, setScrollY] = useState<number>();

  const [backModalVisible, handleBackModalVisible] = useState<boolean>(false);
  const [deliveryModalVisible, handleDeliveryModalVisible] = useState<boolean>(false);
  const [cabReturnModalVisible, handleCabReturnModalVisible] = useState<boolean>(false);
  const [updPhoneVisible, handleUpdPhoneVisible] = useState<boolean>(false);

  const [currentData, setCurrentData] = useState<any>();
  const [stationNames, setStationNames] = useState<any>([]);

  const l_state: any = history.location.state;

  const getScrollY = () => {
    // 计算并设置table内容区域高度
    const windowHeight = document.documentElement.clientHeight;
    const clientTop = document.getElementsByClassName('zkfc-table')[0]?.getBoundingClientRect().top;
    setScrollY(windowHeight - clientTop - 130);
  };

  useEffect(() => {
    $utils.addTab(dispatch, {
      name: '查看历史订单',
      path: '/order/delivery/history',
      state: {},
    });
    if (!initParams) {
      setParams({
        dateTime: moment(l_state.dataTime),
        expCode: l_state.expCode,
      });
    }
  }, []);

  // 筛选重置时更新表单
  useEffect(() => {
    // 初始化时计算高度
    getScrollY();
  }, [initParams]);

  useEffect(() => {
    const getStationNames = async () => {
      try {
        const msg = await getStationName({ name: '' });
        let new_data: API.Select[] = [];
        if (msg.code === 0) {
          msg.body.map((item: { id: number; name: string }) => {
            new_data.push({
              label: item.name,
              value: item.id,
            });
          });
          setStationNames(new_data);
          return;
        }
      } catch (error) {
        console.log(error);
        message.error('驿站名称列表获取失败!');
      }
    };

    getStationNames();
  }, []);

  // 查看手机号
  const inspectPhone = (data: any) => {
    Modal.info({
      className: 'inspect-phone',
      icon: false,
      maskClosable: true,
      closable: true,
      content: (
        <div style={{ textAlign: 'center', fontSize: 28, color: '#000' }}>
          <p>
            {data?.receiver?.phone.substring(0, 3)} {data?.receiver?.phone.substring(3, 7)}{' '}
            {data?.receiver?.phone.substring(7, 11)}
          </p>
          <p>{data?.receiver?.name}</p>
          <p>{data?.expressName}</p>
        </div>
      ),
      onOk() {},
    });
  };

  // 手机扫描模式无
  const getDetailLogImg = async (id: any) => {
    let data = null;
    try {
      const msg = await getDeliveryLog({ id });
      const item = msg.body.find((item: any) => item.op === '入库');
      const explainData = item.explain.split('|');
      if (explainData[1].indexOf('http') > -1) {
        data = explainData[1].substring(explainData[1].indexOf('http'));
      }
    } catch (error) {
      console.log(error);
    }
    return data;
  };

  const columns: ProColumns<any>[] = initParams && [
    {
      title: '入库日期',
      key: 'dateTime',
      dataIndex: 'createdAt',
      valueType: 'dateMonth',
      hideInTable: true,
      fieldProps: {
        disabledDate: (current: any) => {
          // 只可选择90天内，上线日期后
          return !(
            current > moment().subtract(12, 'month') &&
            current < moment().subtract(0, 'month').endOf('month')
          );
        },
      },
    },
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 260,
      fieldProps: {
        maxLength: 30,
      },
      search: {
        transform: (value: any) => ({ expCode: value.replace(/\s*/g, '') }),
      },
      render: (dom, entity) => {
        const handleJump = () => {
          const newTab = {
            name: `查看${entity.expCode}`,
            path: `/order/delivery/list/detail`,
            state: {
              status: 'detail',
              data: entity,
            },
          };
          // 设置当前tab对象
          $utils.setNewTab(dispatch, newTab);
          $utils.addTab(dispatch, newTab);
          history.push({
            pathname: `/order/delivery/list/detail`,
            state: {
              status: 'detail',
              data: entity,
            },
          });
        };
        return (
          <>
            {entity?.status.detained ? (
              <Badge.Ribbon
                style={{ left: '-14px', top: '-16px' }}
                color={'volcano'}
                placement="start"
                text="滞留件"
              >
                <div
                  key={entity.id}
                  style={{ cursor: 'pointer' }}
                  onClick={() => {
                    handleJump();
                  }}
                >
                  <div style={{ paddingTop: '6px' }}>
                    {dom}
                    <Button
                      type="link"
                      icon={<CopyOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        e.nativeEvent.stopImmediatePropagation();
                        $utils.copyCot(entity.expCode);
                      }}
                    />
                  </div>
                  <div>{entity.expressName}</div>
                </div>
              </Badge.Ribbon>
            ) : (
              <div
                key={entity.id}
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  handleJump();
                }}
              >
                <div style={{ paddingTop: '6px' }}>
                  {dom}
                  <Button
                    type="link"
                    icon={<CopyOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      e.nativeEvent.stopImmediatePropagation();
                      $utils.copyCot(entity.expCode);
                    }}
                  />
                </div>
                <div>{entity.expressName}</div>
              </div>
            )}
          </>
        );
      },
    },
    {
      title: '驿站名称',
      dataIndex: 'stationName',
      valueType: 'select',
      width: 160,
      hideInTable: true,
      initialValue: 0,
      search: {
        transform: (value: any) => ({ stationId: value }),
      },
      fieldProps: {
        showSearch: true,
        options: [{ label: '全部驿站名称', value: 0 }].concat(stationNames),
        placeholder: '请输入内容',
      },
    },
    {
      title: '取件码',
      dataIndex: 'pickupCode',
      valueType: 'textarea',
      search: false,
      width: 160,
      render: (dom, entity) => {
        const storeModeData = storageTypes.find((item: any) => item.value === entity.storeMode);
        return (
          <div key={entity.id}>
            <div style={{ fontWeight: 'bold' }}>
              {dom}({entity.storeMode === 2 ? '货架' : storeModeData?.label})
            </div>
            <div>{entity?.checkinTime}</div>
          </div>
        );
      },
    },
    {
      title: '存放位置',
      dataIndex: 'addr',
      valueType: 'textarea',
      width: 160,
      search: false,
    },
    {
      title: '收件人',
      dataIndex: 'receiver',
      // sorter: true,
      search: false,
      hideInForm: true,
      width: 120,
      render: (dom, entity) => {
        const phone = entity?.receiver?.phone
          ? entity?.receiver?.phone.slice(0, 3) + '****' + entity?.receiver?.phone.slice(-4)
          : '';
        const canChange = [1, 2].includes(entity?.status.bill);
        return (
          <div key={entity.id}>
            <div
              onClick={() => {
                entity?.receiver?.phone && inspectPhone(entity);
              }}
            >
              {entity?.receiver?.name ? entity?.receiver?.name.slice(0, 1) + '**' : ''}
            </div>
            {
              <div
                onClick={() => {
                  entity?.receiver?.phone && inspectPhone(entity);
                }}
              >
                {entity?.receiver?.phone ? phone : '--'}
                {canChange && (
                  <EditOutlined
                    onClick={async (e) => {
                      e.stopPropagation();
                      e.nativeEvent.stopImmediatePropagation();
                      // 修改手机号弹窗
                      if (entity.checkinMode === 1) {
                        const img = await getDetailLogImg(entity.id);
                        img && Object.assign(entity, { scanImg: img });
                      }
                      setCurrentData(entity);
                      handleUpdPhoneVisible(true);
                    }}
                  />
                )}
              </div>
            }
            {entity?.status?.blacklist && entity?.status.bill === 1 && (
              <div>
                <Tag color="#f50">黑名单用户</Tag>
              </div>
            )}
            {!entity?.receiver?.phone && entity?.checkinMode === 2 && (
              <div>
                {entity?.status?.ocr === 3 && (
                  <div style={{ color: 'red', fontWeight: 'bold' }}>OCR识别失败</div>
                )}
                {entity?.status?.ocr === 1 && <div style={{ fontWeight: 'bold' }}>OCR识别中</div>}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '投递类型',
      align: 'center',
      dataIndex: 'deliveryWay',
      valueType: 'select',
      search: false,
      width: 80,
      fieldProps: {
        options: deliveryWayData,
      },
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      search: false,
      order: 6,
      width: 170,
      valueType: 'select',
      fieldProps: {
        placeholder: '全部订单状态',
        options: billStatusTypes,
      },
      render: (dom, entity) => {
        return (
          <div key={entity.id}>
            <div>{statusData[entity.status.bill - 1]}</div>
            <div>
              {/* 待出库 、待核对手机号 才显示按钮，否则显示时间 */}
              {[1, 2, 5, 6, 7].includes(entity.status.bill) ? (
                <Space>
                  <Button
                    type="primary"
                    size={'small'}
                    onClick={() => {
                      setCurrentData(entity);
                      handleDeliveryModalVisible(true);
                    }}
                  >
                    点此出库
                  </Button>
                </Space>
              ) : (
                <div>{entity.status.bill == 3 ? entity.checkoutTime : entity.returnTime}</div>
              )}
            </div>
          </div>
        );
      },
    },
  ];

  const reqHistoryOrderList = async () => {
    const data = formRef?.current?.getFieldsValue();
    if (!data.dateTime) {
      message.info('请选择入库日期！');
      return;
    }
    if (!data.expCode) {
      message.info('请输入运单号！');
      return;
    }
    const params = {
      startTime: moment(data.dateTime).startOf('month').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment(data.dateTime).endOf('month').format('YYYY-MM-DD HH:mm:ss'),
      expCode: data.expCode,
    };
    // 202302281794
    const msg = await historyOrderList(params);
    if (msg.code === 0) {
      $utils.addTab(dispatch, {
        name: '查看历史订单',
        path: '/order/delivery/history',
        isTopMenu: true,
        state: {
          dataTime: moment(data.dateTime).format('YYYY-MM'),
          expCode: data.expCode,
        },
      });
      setParams(data);
      setDataSource(msg.body || []);
    }
  };

  return (
    <PageContainer>
      {initParams && (
        <ProTable<API.RuleListItem, API.PageParams>
          actionRef={actionRef}
          formRef={formRef}
          rowKey="id"
          tableClassName="zkfc-table"
          form={{
            initialValues: initParams,
          }}
          scroll={{
            y: scrollY || 0,
          }}
          search={{
            labelWidth: 80,
            collapsed: collapsed,
            onCollapse: (collapsed: boolean) => {
              setCollapsed(collapsed);
              getScrollY();
              actionRef?.current?.reload && actionRef?.current?.reload();
            },
            span: 6,
            optionRender: (searchConfig, formProps, dom) => [
              <Button type="primary" key="resetQuery" onClick={() => reqHistoryOrderList()}>
                查询
              </Button>,
              <Button
                key="resetText"
                onClick={() => {
                  formRef?.current?.setFieldsValue({
                    dateTime: moment(),
                    expCode: undefined,
                    stationName: 0,
                  });
                }}
              >
                重置
              </Button>,
            ],
          }}
          toolBarRender={false}
          options={false}
          dataSource={dataSource}
          footer={() => false}
          request={async (params) => {
            return {
              data: [],
              success: true,
            };
          }}
          columns={columns}
        />
      )}
      <ModalForm
        title={'修改手机号'}
        modalProps={{
          centered: true,
          destroyOnClose: true,
          onCancel: () => {
            setCurrentData(null);
          },
        }}
        width="950px"
        labelCol={{ span: 6 }}
        visible={updPhoneVisible}
        initialValues={{
          ...currentData,
          old_phone: currentData?.receiver.phone || '--',
        }}
        onVisibleChange={handleUpdPhoneVisible}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            phone: value.phone,
          };
          const msg = await changePhone(params);
          if (msg.code === 0) {
            message.success('修改成功!');
            setCurrentData(null);
            actionRef.current?.reload();
            handleUpdPhoneVisible(false);
          }
        }}
      >
        <Row gutter={16}>
          <Col
            span={12}
            style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}
          >
            <ProFormText
              label="运单号"
              disabled
              rules={[
                {
                  required: true,
                },
              ]}
              width="md"
              name="expCode"
            />
            <ProFormText
              label="入库时间"
              disabled
              rules={[
                {
                  required: true,
                },
              ]}
              width="md"
              name="checkinTime"
            />
            <ProFormText
              label="原手机号"
              disabled
              rules={[
                {
                  required: true,
                },
              ]}
              width="md"
              name="old_phone"
            />
            <ProFormText
              label="新手机号"
              placeholder={'请输入新的客户手机号'}
              rules={[
                { required: true },
                { len: 11, message: '请输入11位手机号' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (value && getFieldValue('old_phone') === value) {
                      return Promise.reject(new Error('新手机号不能与原手机号相同'));
                    }
                    return Promise.resolve();
                  },
                }),
              ]}
              width="md"
              name="phone"
            />
            <div
              style={{
                fontSize: 12,
                color: 'rgba(16, 16, 16, 100)',
                marginTop: 42,
                textAlign: 'center',
              }}
            >
              注意：如订单需要支付取件费或延期费，修改手机号后将重新计费！
            </div>
          </Col>
          <Col span={12} style={{ display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
            <div
              style={{
                width: '100%',
                padding: '10px 15%',
                display: 'flex',
                justifyContent: 'space-around',
                alignItems: 'center',
                fontSize: '32px',
                color: '#1890FF',
              }}
            >
              <MyIcon
                type="icon-a-shunshizhenxuanzhuan90"
                onClick={() => {
                  handleUpdRotation(rotation + 90);
                }}
              />
              <MyIcon
                type="icon-a-nishizhenxuanzhuan90"
                onClick={() => {
                  handleUpdRotation(rotation - 90);
                }}
              />
              <MyIcon
                type="icon-a-shunshizhenxuanzhuan180"
                onClick={() => {
                  handleUpdRotation(rotation + 180);
                }}
              />
            </div>
            <div style={{ width: 360, height: 360, overflow: 'hidden' }}>
              {currentData?.ocrImageTimeout ? (
                <div
                  style={{
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#E8E8E8',
                  }}
                >
                  图片已过期(保存30天)
                </div>
              ) : currentData?.ocrImage || currentData?.scanImg ? (
                <Image
                  src={currentData?.ocrImage || currentData?.scanImg}
                  style={{
                    width: 360,
                    height: 360,
                    zoom: `${img_zoom}%`,
                    transform: `scale3d(1, 1, 1) rotate(${rotation}deg)`,
                  }}
                  preview={{
                    getContainer: false,
                  }}
                  alt=""
                />
              ) : (
                <div
                  style={{
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#E8E8E8',
                  }}
                >
                  该订单为手动输入，无入库底单
                </div>
              )}
            </div>
            {!currentData?.ocrImageTimeout && (currentData?.ocrImage || currentData?.scanImg) && (
              <div style={{ marginTop: 20, width: '100%', padding: '0 12%', display: 'flex' }}>
                <Button
                  type="primary"
                  onClick={() => {
                    $utils.handleDownImage(currentData?.ocrImage || currentData?.scanImg);
                  }}
                >
                  下载图片
                </Button>
              </div>
            )}
          </Col>
        </Row>
      </ModalForm>
      <ModalForm
        title={'退回'}
        modalProps={{
          centered: true,
        }}
        width="400px"
        labelCol={{ span: 6 }}
        visible={backModalVisible}
        onVisibleChange={handleBackModalVisible}
        initialValues={{
          ...currentData,
        }}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            reason: value.reason,
            comment: value.comment || '',
          };
          const msg = await billReturn(params);
          if (msg.code === 0) {
            message.success('操作成功');
            setCurrentData(null);
            actionRef.current?.reload();
            handleBackModalVisible(false);
          }
        }}
      >
        <ProFormText
          label="运单号"
          disabled={true}
          width="md"
          name="expCode"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormText
          label="入库时间"
          width="md"
          disabled={true}
          name="checkinTime"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormSelect
          width="md"
          name="reason"
          label="退回原因"
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            options: reasonList,
          }}
        />
        <ProFormTextArea
          label="备注"
          fieldProps={{ maxLength: 50, placeholder: '请输入备注,最多50字' }}
          rules={[{ max: 50 }]}
          width="md"
          name="comment"
        />
      </ModalForm>
      <ModalForm
        title={'出库'}
        modalProps={{
          centered: true,
        }}
        width="360px"
        labelCol={{ span: 6 }}
        visible={deliveryModalVisible}
        onVisibleChange={handleDeliveryModalVisible}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            open: value.open - 1,
          };
          const msg = await deliveryCheckout(params);
          if (msg.code === 0) {
            message.success('操作成功');
            setCurrentData(null);
            actionRef.current?.reload();
            handleDeliveryModalVisible(false);
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            options:
              +currentData?.storeMode === 3
                ? [
                    { label: '仅出库', value: 1 },
                    { label: '开箱并出库', value: 2 },
                  ]
                : [{ label: '出库', value: 1 }],
          }}
          width="md"
          name="open"
        />
        <p style={{ textAlign: 'center' }}>提示: 此处出库后，驿站账户将不再获得收入</p>
      </ModalForm>
      <ModalForm
        title={'提示'}
        modalProps={{
          centered: true,
        }}
        width="360px"
        labelCol={{ span: 6 }}
        visible={cabReturnModalVisible}
        onVisibleChange={handleCabReturnModalVisible}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            open: value.open,
          };
          const msg = await billReturn(params);
          if (msg.code === 0) {
            message.success('操作成功');
            setCurrentData(null);
            actionRef.current?.reload();
            handleCabReturnModalVisible(false);
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            options: [
              { label: '仅退回', value: 0 },
              { label: '开箱并退回', value: 1 },
            ],
          }}
          width="md"
          name="open"
        />
        <p style={{ textAlign: 'center' }}>退回后，请及时到柜体取出包裹！</p>
      </ModalForm>
    </PageContainer>
  );
};

export default DeliveryList;
